<template>
  <div>
    <slot></slot>
  </div>
</template>

<script>
export default {
  model: {
    event: 'change'
  },
  props: {
    value: null,
    // 间隔多久时间没活动之后自动'睡眠'，毫秒单位
    activeDuration: {
      type: Number,
      default: 3000
    },
    // 唤醒事件
    onEvent: {
      type: [String, Array],
      default: 'mousemove'
    },
    once: {
      type: Boolean,
      default: true
    }
  },
  watch: {
    value(active) {
      if (active) {
        this._wakeUp();
      } else {
        this._sleep();
      }
    }
  },
  mounted() {
    this.useModel = typeof this.value != 'undefined';
    this.sleeping = this.useModel ? !this.value : false
    this.lastActiveTime = +new Date();
    let timer;

    const tick = () => {
      if ((+new Date() - this.lastActiveTime) > this.activeDuration) {
        this._sleep();
      }
      timer = setTimeout(tick, this.activeDuration);
    };

    const eventHandler = () => {
      this._wakeUp();
    };
    const onEvents = typeof this.onEvent == 'string' ? [this.onEvent] : this.onEvent;
    onEvents.forEach(event => {
      document.addEventListener(event, eventHandler);
    });
    this.$once('hook:beforeDestroy', () => {
      clearTimeout(timer);
      onEvents.forEach(event => {
        document.removeEventListener(event, eventHandler);
      });
    });

    tick();
  },
  methods: {
    _wakeUp() {
      this.lastActiveTime = +new Date();
      if (!this.sleeping && this.once) return;
      this.sleeping = false;
      this.$emit('wake');
      if (this.useModel) {
        this.$emit('change', true);
      }
    },
    _sleep() {
      if (this.sleeping && this.once) return;
      this.sleeping = true;
      this.$emit('sleep');
      if (this.useModel) {
        this.$emit('change', false);
      }
    }
  }
}
</script>